package com.dobby.pea.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dobby.pea.common.BaseContext;
import com.dobby.pea.common.CustomException;
import com.dobby.pea.common.R;
import com.dobby.pea.dto.GoodDto;
import com.dobby.pea.dto.OrderDto;
import com.dobby.pea.entity.*;
import com.dobby.pea.service.*;
import lombok.extern.slf4j.Slf4j;
import com.dobby.pea.mapper.OrderMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, tbOrder> implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private UserService userService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private GoodService goodService;

    @Autowired
    private GoodSalesService goodSalesService;

    //传入商品id 返回订单细节

    /**
     * 用户购物车下单
     * @param ids
     * @return
     */
    @Transactional
    public tbOrder submit(List<Long> ids) {
        tbOrder order = new tbOrder();
        //获得当前用户id
        Long userId = BaseContext.getCurrentId();

        LambdaQueryWrapper<tbShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(tbShoppingCart::getUserId,userId);
        queryWrapper.in(tbShoppingCart::getId,ids);
        List<tbShoppingCart> shoppingCarts = shoppingCartService.list(queryWrapper);

        if(shoppingCarts == null || shoppingCarts.size() == 0){
            throw new CustomException("购物车数据异常，不能下单");
        }

        long orderId = IdWorker.getId();// mybatis-plus雪花算法增强:idworker 生成订单号
        AtomicInteger amount = new AtomicInteger(0);//AtomicInteger线程安全的加减操作接口


        List<tbOrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            tbOrderDetail orderDetail = new tbOrderDetail();
            orderDetail.setOrderId(orderId);
            //设置为待付款
            orderDetail.setStatus(1);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setGoodId(item.getGoodId());
            tbGood good = goodService.getById(item.getGoodId());
            BigDecimal number = new BigDecimal(item.getNumber());
            BigDecimal price = good.getPrice();
            orderDetail.setAmount(price.multiply(number));
            amount.addAndGet(price.multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //向订单明细表插入数据，多条数据
        orderDetailService.saveBatch(orderDetails);

        tbAddressBook addressBook = addressBookService.DefaultAddressBook(userId);


        order.setId(orderId);
        order.setUserId(userId);
        //设置为待付款
        order.setStatus(1);
        order.setAddressBookId(addressBook.getId());
        order.setOrderTime(LocalDateTime.now());
        order.setCheckoutTime(LocalDateTime.now());
        order.setIsDeleted(0);
        order.setAmount(new BigDecimal(amount.get()));
        this.save(order);

        return order;
        //清空购物车数据
//        shoppingCartService.removeByIds(ids);
    }

    @Transactional
    public R<String> orders(tbOrder order) {
//        根据订单更新该用户的 账户余额
        tbUser user = userService.getById(order.getUserId());
        log.info("当前订单总额：{}", order.getAmount());
        BigDecimal amount = user.getMoney().subtract(order.getAmount());
//        a = -1,表示bigdemical小于bigdemical2；
        if (amount.compareTo(BigDecimal.valueOf(0))==-1)  return R.error("下单失败");
        log.info("订单正常");
        user.setMoney(amount);
        userService.updateById(user);

        //更新订单数据
        UpdateWrapper<tbOrder> UpdateWrappertbOrder = new UpdateWrapper<>();
        UpdateWrappertbOrder.eq("id",order.getId());
        log.info("当前地址id：{}", order.getAddressBookId());
        UpdateWrappertbOrder.set("address_book_id",order.getAddressBookId());
        UpdateWrappertbOrder.set("status",2);
        this.update(UpdateWrappertbOrder);

        //更新订单细节数据
        UpdateWrapper<tbOrderDetail> UpdateWrappertbOrderDetail = new UpdateWrapper<>();
        UpdateWrappertbOrderDetail.in("order_id",order.getId());
        UpdateWrappertbOrderDetail.set("status",2);
        orderDetailService.update(UpdateWrappertbOrderDetail);

        LambdaQueryWrapper<tbOrderDetail> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(tbOrderDetail::getOrderId,order.getId());
        List<tbOrderDetail> list = orderDetailService.list(queryWrapper);

        for (tbOrderDetail tbOrderDetail : list) {
            Long goodId = tbOrderDetail.getGoodId();
            tbGood good = goodService.getById(goodId);
            goodSalesService.SalesAddOne(good);
        }

        return R.success("下单成功");
    }

    @Transactional
    public R<Page> orderDtoPage(int page, int pageSize,Long id) {
        //构造分页构造器对象
        Page<tbOrder> orderPage = new Page<>(page,pageSize);
        Page<OrderDto> orderDtoPage = new Page<>();

        LambdaQueryWrapper<tbOrder> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(tbOrder::getUserId,id);
        queryWrapper.orderByDesc(tbOrder::getOrderTime);

        //执行分页查询
        this.page(orderPage,queryWrapper);

        //对象拷贝
        BeanUtils.copyProperties(orderPage,orderDtoPage,"records");

        List<tbOrder> records = orderPage.getRecords();
        List<OrderDto> list = records.stream().map((item) -> {
            OrderDto orderDto = new OrderDto();

            BeanUtils.copyProperties(item,orderDto);

            Long orderId = item.getId();
            Long userId = item.getUserId();
            Long addressBookId = item.getAddressBookId();
            //根据id查询用户对象
            tbUser user = userService.getById(userId);
            //根据id查询订单细节对象
            LambdaQueryWrapper<tbOrderDetail> queryWrappertbOrderDetail= new LambdaQueryWrapper<>();
            queryWrappertbOrderDetail.eq(tbOrderDetail::getOrderId,orderId);
            List<tbOrderDetail> tbOrderDetails = orderDetailService.list(queryWrappertbOrderDetail);
            //根据id查询地址对象
            tbAddressBook addressBook = addressBookService.getById(addressBookId);

            orderDto.setUser(user);
            orderDto.setOrderDetails(tbOrderDetails);
            orderDto.setAddressBook(addressBook);

            return orderDto;
        }).collect(Collectors.toList());

        orderDtoPage.setRecords(list);

        return R.success(orderDtoPage);

    }

    /**
     * 根据订单id 返回订单
     * @param id
     * @return
     */
    @Transactional
    public OrderDto OrderById(Long id) {

        log.info("id---------------->{}",id);
        OrderDto orderDto = new OrderDto();

        tbOrder order = this.getById(id);

        log.info("该订单数据初始生成------->{}",order);

        LambdaQueryWrapper<tbOrderDetail> queryWrapper= new LambdaQueryWrapper<>();
        queryWrapper.eq(tbOrderDetail::getOrderId,id);
        List<tbOrderDetail> list = orderDetailService.list(queryWrapper);


        BeanUtils.copyProperties(order,orderDto);

        tbUser user = userService.getById(order.getUserId());

        tbAddressBook addressBook = addressBookService.getById(order.getAddressBookId());


        orderDto.setUser(user);
        orderDto.setAddressBook(addressBook);
        orderDto.setOrderDetails(list);

        return orderDto;


    }

    @Transactional
    public R<List<OrderDto>> orderByGood(Long id) {
        log.info("id---->{}",id);
        List<tbOrderDetail> tbOrderDetails = orderDetailService.OrderDetailById(id);

        List<OrderDto> list = tbOrderDetails.stream().map((item) -> {
            OrderDto orderDto = new OrderDto();

            //原订单id取出 查找订单
            Long orderId = item.getOrderId();
            tbOrder order = this.getById(orderId);

            tbUser user = userService.getById(order.getUserId());
            tbAddressBook addressBook = addressBookService.getById(order.getAddressBookId());

            orderDto.setUser(user);
            orderDto.setAddressBook(addressBook);
//            List<tbOrderDetail> orderDtos = new ArrayList<>();
//            orderDtos.add(item);
//            orderDto.setOrderDetails(orderDtos);
            orderDto.getOrderDetails().add(item);


            return orderDto;
        }).collect(Collectors.toList());


        return R.success(list);
    }

    @Transactional
    public String updateOrderDetail(tbOrderDetail tbOrderDetail) {
        //修改订单的细节
        orderDetailService.updateById(tbOrderDetail);

        //查询该订单 接下来判断该订单下的 订单细节状态是否都以送达 要是已送达 更改总订单的状态
        OrderDto orderDto = this.OrderById(tbOrderDetail.getOrderId());

        List<tbOrderDetail> orderDetails = orderDto.getOrderDetails();


        int statusFlag = 0;
        for (tbOrderDetail orderDetail : orderDetails) {
            int status = orderDetail.getStatus();
            if (status!=4){
                statusFlag=1;
            }
        }
        if (statusFlag==0){
            UpdateWrapper<tbOrder> UpdateWrappertbOrder = new UpdateWrapper<>();
            UpdateWrappertbOrder.in("id",tbOrderDetail.getOrderId());
            UpdateWrappertbOrder.set("status",3);
            this.update(UpdateWrappertbOrder);
        }

        return "修改成功";
    }

}